/*
 * @Author: your name
 * @Date: 2021-09-15 09:34:48
 * @LastEditTime: 2021-09-16 13:45:08
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \media_system\routes\index.js
 */
const { Sequelize, DataTypes } = require("sequelize");
const moment = require('moment');
const { User, Hemoglobin, Food } = require('../database/index')
const Router = require('@koa/router')
const { formatResponse,filterColumn } = require("../utils/common");
const router = new Router()

/**
 * @swagger
 *  /hemoglobin/add: #接口访问路径(拼接上之前swagger.js中的host)
 *    post: #请求方式
 *     summary: 添加当前用户糖化血红蛋白  #接口信息
 *     description: 添加当前糖化血红蛋白 #接口描述
 *     tags: [血糖记录] #接口分组
 *     produces:
 *       - application/json
 *     requestBody:
 *         content:
 *            application/x-www-form-urlencoded:
 *               schema:
 *                  type: object
 *                  required:
 *                  - hemoglobinValue
 *                  - recordTime
 *                  - userId
 *                  properties:
 *                    userId:
 *                      type: string
 *                      description: 用户ID
 *                    hemoglobinValue:
 *                      type: number
 *                      description: 血糖值
 *                    recordTime:
 *                      type: string
 *                      description: 记录时间,格式为2023-09-22 16:41:23
 *                      pattern: "yyyy-MM-dd HH:mm:ss"
 *                      example: "2023-09-22 16:41:23"
 *     responses: #返回结果
 *       200:
 *         description: 成功
 */
router.post("/add", async function (ctx, next) {
  let hemoglobin = ctx.request.body;
  // console.log("bloodglucose:", bloodglucose);
  const cHemoglobin = await Hemoglobin.create({
    hemoglobinValue: hemoglobin.hemoglobinValue,
    recordTime: hemoglobin.recordTime,
  });
  const cuser = User.build({
    userId:hemoglobin.userId
  })
  await cHemoglobin.setUser(cuser)

  if (cHemoglobin) {
    ctx.body = formatResponse("200", { ...cHemoglobin.get({ plain: true }) }, "success");
  } else {
    ctx.body = formatResponse("500", "", "fail");
  }
});


/**
 * @swagger
 * /hemoglobin/getHemoglobinByDates:
 *   get:
 *     security:
 *       - bearerAuth: []
 *     summary: 查询当前用户指定时间段的糖化血红蛋白信息
 *     description: 查询当前用户指定时间段的糖化血红蛋白信息
 *     tags: [血糖记录]
 *     parameters:
 *       - name: userId
 *         in: query #参数存放位置。query是存放到请求头里边
 *         required: true
 *         description: 用户id
 *         type: string
 *       - name: startDate
 *         in: query #参数存放位置。query是存放到请求头里边
 *         required: true
 *         description: 起始日期,例如2017-07-21
 *         type: string
 *       - name: endDate
 *         in: query #参数存放位置。query是存放到请求头里边
 *         required: true
 *         description: 结束日期,例如2017-07-21
 *         type: string
 *     responses:
 *       200:
 *         description: 成功
 */
router.get("/getHemoglobinByDates", async function (ctx, next) {
  const { userId,startDate,endDate } = ctx.request.query;
  const Op = Sequelize.Op;
  const DATE_START = moment(startDate).format('YYYY-MM-DD 00:00:00');
  const DATE_END = moment(endDate).format('YYYY-MM-DD 23:59:00');
  let hemoglobins = await Hemoglobin.findAll({
    where: { 
      userId,
      recordTime: { 
        [Op.between]: [
          DATE_START,
          DATE_END,
      ]
      },
     },
    include: {
      model: User,
      attributes: ['username','userId','weight','bmi'] 
    }
  });
  // console.log(hemoglobins);//findAll返回的数组对象，不需要使用get({ plain: true }
  if (hemoglobins.length>=0) {
    ctx.body = formatResponse("200", hemoglobins.length>0?hemoglobins:[], "success");
  } else {
    ctx.body = formatResponse("500", "", "fail");
  }
});
/**
 * @swagger
 * /hemoglobin/deleteHemoglobins:
 *   get:
 *     security:
 *       - bearerAuth: []
 *     summary: 根据血红蛋白ID删除血红蛋白记录
 *     description: 根据血红蛋白ID删除血红蛋白记录
 *     tags: [血糖记录]
 *     parameters:
 *       - name: hemoglobinIds
 *         in: query #参数存放位置。query是存放到请求头里边
 *         required: true
 *         description: 血红蛋白ID
 *         schema:
 *          type: array
 *          items:
 *            type: string
 *     responses:
 *       200:
 *         description: 成功
 */
router.get("/deleteHemoglobins", async function (ctx, next) {
  const { hemoglobinIds } = ctx.request.query;
  const count = await Hemoglobin.destroy({
    where: {
      hemoglobinId: hemoglobinIds
    }
  });
  if (count > 0) {
    ctx.body = formatResponse("200", {code:200,message:'糖化血红蛋白删除成功'}, "success");
  } else {
    ctx.body = formatResponse("500", "", "fail");
  }
});
/**
 * @swagger
 * /hemoglobin/getHemoglobinByPageAndCondition:
 *   get:
 *     security:
 *       - bearerAuth: []
 *     summary: 条件分页查询糖化血红蛋白记录
 *     description: 条件分页查询糖化血红蛋白记录
 *     tags: [血糖记录]
 *     parameters:
 *       - name: userId
 *         in: query #参数存放位置。query是存放到请求头里边
 *         description: 用户ID
 *         type: string
 *       - name: username
 *         in: query #参数存放位置。query是存放到请求头里边
 *         description: 用户名称
 *         type: string
 *       - name: currentPage
 *         in: query #参数存放位置。query是存放到请求头里边
 *         required: true
 *         description: 当前第几页
 *         type: string
 *       - name: pageSize
 *         in: query #参数存放位置。query是存放到请求头里边
 *         required: true
 *         description: 一页几条记录
 *         type: string
 *     responses:
 *       200:
 *         description: 成功
 */
router.get("/getHemoglobinByPageAndCondition", async function (ctx, next) {
  const { currentPage, pageSize, userId,username} = ctx.request.query;
  offset = (currentPage - 1) * pageSize || 0;
  const condition1 =username? { username } : null ;
  const condition2 =userId? { userId } : null ;
  let result = await Hemoglobin.findAndCountAll({
    order: [['createdAt', 'DESC']],
    offset,
    limit: parseInt(pageSize),
    include:{
      model: User,
      where:Object.assign({}, condition1,condition2), 
      attributes: ['username','realname','weight','bmi','specialCondition'],
    }
  });
  if (result) {
    ctx.body = formatResponse("200", result, "success");
  } else {
    ctx.body = formatResponse("500", "", "fail");
  }
});

/**
 * @swagger
 * /hemoglobin/updateHemoglobin: #接口访问路径(拼接上之前swagger.js中的host)
 *   post: #请求方式
 *     security:
 *       - bearerAuth: []
 *     summary: 根据血红蛋白ID更新血红蛋白信息  #接口信息
 *     description: 根据血红蛋白ID更新血红蛋白信息 #接口描述
 *     tags: [血糖记录] #接口分组
 *     produces:
 *       - application/json
 *     consumes:
 *       - application/json
 *     requestBody:
 *         content:
 *            application/x-www-form-urlencoded:
 *               schema:
 *                  type: object
 *                  properties:
 *                     hemoglobinId:          # <!--- form field name
 *                        type: string
 *                        description: 糖化血红蛋白ID
 *                     hemoglobinValue:          
 *                        type: number
 *                        description: 糖化血红蛋白值
 *                     recordTime:       
 *                        type: string
 *                        description: 记录时间
 *     responses: #返回结果
 *       200:
 *         description: 成功
 */
router.post("/updateHemoglobin", async function (ctx, next) {
  try {
    let hemogInfo = ctx.request.body;
    hemogInfo = filterColumn(hemogInfo)
    // console.log(1111111111111,hemogInfo)
    let result = await Hemoglobin.update(
      {
        ...hemogInfo
      },
      {
        where: {
          hemoglobinId: hemogInfo.hemoglobinId,
        },
      }
    );
    if (result[0] > 0) {
      ctx.body = formatResponse("200", { code: 200, message: '糖化血红蛋白更新成功' }, "success");
    } else {
      ctx.body = formatResponse("500", { code: 500, message: '糖化血红蛋白更新失败' }, "fail");
    }
  } catch (error) {
    ctx.body = formatResponse("500", error, "fail");
  }

});
module.exports = router